﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FluentValidation.Results;
using Spaanjaars.ContactManager.Infrastructure.Validation;
using Spaanjaars.ContactManager.Services.Commands;
using Spaanjaars.ContactManager.Services.Interfaces;

namespace Spaanjaars.ContactManager.UX.MVC.Controllers
{
    public class ContactPersonAddController : Controller
    {
        private readonly IContactPersonCreationService _contactPersonCreationService;

        public ContactPersonAddController(IContactPersonCreationService contactPersonCreationService)
        {
            _contactPersonCreationService = contactPersonCreationService;
        }

        //
        // GET: /ContactPersonAdd/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(CreateContactPersonCommand createContactPersonCommand)
        {
            CreateContactPersonCommandResult result = _contactPersonCreationService.CreatePersonFrom(createContactPersonCommand);

            if (result.HasErrors)
            {
                foreach(IBrokenRule brokenRule in result.BrokenRules)
                {
                    ModelState.AddModelError(brokenRule.PropertyName, brokenRule.BrokenRuleMessage);
                }

                return View(createContactPersonCommand);
            }            
            else
                return RedirectToAction("Index", "ContactPersonList");
        }
    }
}
